package system

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"shopstar/core/cache"
	systemreq "shopstar/forms/api/system"
	"shopstar/global"
	"shopstar/reponse"
	systemresp "shopstar/reponse/system"
	"shopstar/util"
	"time"
)

// 发送手机短信的验证码方法
func SmsCode(ctx *gin.Context) {
	// 1.获取手机号
	smsreq := new(systemreq.Sms)
	// 2.利用验证器原则手机号的正确性
	if err := ctx.ShouldBind(smsreq); err != nil {
		//ctx.String(http.StatusOK, err.Error())
		reponse.HandleValidateError(ctx, err)
		return
	}
	//ctx.String(http.StatusOK, "ok , ok")

	// 3.发送短信(测试 -- 暂时关闭)
	code := util.GenValidateCode(global.Config.Sms.Long)
	//content := fmt.Sprintf(global.Config.Sms.Temp.Code, code, global.Config.Sms.Overdue)
	//_, err := sms.NewSms(global.Config.Sms.Service).Send(smsreq.Phone, content)
	//if err != nil {
	//	reponse.FailWithMsg("短信发送失败", ctx)
	//	return
	//}
	// 存储 => 缓存中 key
	// key =》 手机号、时间戳、或者手机号+时间戳、随机定长的key
	key := util.GenValidateCode(15)
	cache.CacheManager.Set(key, []byte(code), &cache.Options{
		Expiration: time.Duration(global.Config.Sms.Overdue) * time.Second,
	})

	// 6.返回
	reponse.OKWithData(&gin.H{
		"verification_key": key,
		"expired_at":       global.Config.Sms.Overdue,
		"code":             code,
	}, ctx)
}

// 图形验证码
func Captcha(ctx *gin.Context) {
	driver := base64Captcha.NewDriverDigit(
		global.Config.Captcha.ImgHeight,
		global.Config.Captcha.ImgWidth,
		global.Config.Captcha.KeyLong,
		0.7,
		80,
	)
	cp := base64Captcha.NewCaptcha(driver, global.CaptchaStore)

	id, base64, a, err := cp.Generate()
	if err != nil {
		reponse.FailWithMsg("验证码获取错误", ctx)
		return
	}
	fmt.Println(a)
	//fmt.Println(id, answer)
	reponse.OKWithDatailed(systemresp.CaptchaResp{
		CaptchaId: id,
		PicPath:   base64,
	}, "验证码获取成功", ctx)
}
